package com.ssm.juc.synchronized1;

import lombok.extern.slf4j.Slf4j;
import org.openjdk.jol.info.ClassLayout;

/**
 * 触发场景：创建子线程去获取锁
 * <p>
 * 偏向锁状态
 * <p>
 * 测试例子1: 调用 hashcode, 升级为重量级锁
 * 测试例子2: 调用 notify, 偏向锁升级为轻量级锁
 * 测试例子3: 调用 wait, 偏向锁升级为重量级锁
 */
@Slf4j
public class BiasedLockStateTest {

    public static void main(String[] args) throws InterruptedException {
        log.debug(ClassLayout.parseInstance(new Object()).toPrintable());
        Thread.sleep(4000);
        Object obj1 = new Object();
        log.debug(ClassLayout.parseInstance(obj1).toPrintable());
        new Thread(new Runnable() {
            @Override
            public void run() {
                log.info("threadId:" + ClassLayout.parseInstance(obj1));
                log.debug("start ... \r\n" + ClassLayout.parseInstance(obj1).toPrintable());
                synchronized (obj1) {
                    log.debug("lock ... \r\n" + ClassLayout.parseInstance(obj1).toPrintable());
                    //测试例子1: 调用 hashcode, 升级为重量级锁
//                    obj1.hashCode();
//                    log.debug("invoke hashCode method ... \r\n" + ClassLayout.parseInstance(obj1).toPrintable());

                    //测试例子2: 调用 notify, 偏向锁升级为轻量级锁
//                    obj1.notify();
//                    log.debug("invoke notify method ... \r\n" + ClassLayout.parseInstance(obj1).toPrintable());

                    //测试例子3: 调用 wait, 偏向锁升级为重量级锁
//                    try {
//                        obj1.wait(3);
//                    } catch (InterruptedException e) {
//                        throw new RuntimeException(e);
//                    }
                    log.debug("invoke wait method ... \r\n" + ClassLayout.parseInstance(obj1).toPrintable());
                }
                log.debug("unlock ... \r\n" + ClassLayout.parseInstance(obj1).toPrintable());
            }
        }, "thread0").start();

        Thread.sleep(5000);
        log.debug(ClassLayout.parseInstance(obj1).toPrintable());
    }
}